<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-row>
        <!-- 项目编号 -->
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectNumber">
            <el-select v-model="dataForm.projectNumber" placeholder="请选择项目编号" class="label_len" :disabled="selectDis">
              <el-option v-for="item in projectList" :key="item.prProjectNumber"
                :label="item.prProjectNumber + item.prProjectName" :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 测定日期 -->
        <el-col :span="12">
          <el-form-item label="测定日期" prop="dataTime">
            <el-date-picker v-model="dataForm.dataTime" type="datetime" placeholder="请选择测定日期" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!--下拉多选框-->
      <el-col :span="12">
        <el-form-item label="仪器型号" prop="instrumentModels">
          <el-select v-model="dataForm.selectedModels" multiple placeholder="请选择仪器型号" class="label_len"
            style="width: 500px;" @change="handleModelSelectionChange">
            <el-option v-for="item in instrumentList" :key="item.instrumentNumber"
              :label="`(${item.instrumentNumber})-(${item.instrumentName})-(${item.accuracyRating})-(${item.measuringRange})`"
              :value="item.instrumentNumber">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-table :data="tableData" border style="margin-top: 20px; text-align: center;">
        <el-table-column label="仪器型号名称" prop="instrumentName" width="200"></el-table-column>
        <el-table-column label="编号" prop="instrumentNumber" width="100"></el-table-column>
        <el-table-column label="准确度" prop="keyInstrument" width="100"></el-table-column>
        <el-table-column label="量程" prop="valueTa" width="100"></el-table-column>
        <el-table-column label="有效期" prop="indate">
          <template slot-scope="scope">
            <!-- 时间范围选择器 -->
            <el-date-picker v-model="scope.row.indate" type="daterange" format="yyyy-MM-dd" placeholder="选择有效期"
              range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" @change="handleDateChange(scope)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        projectNumber: '',
        dataTime: '',
        inspector: '',
        notekeeper: '',
        checker: '',
        pdfPath: '',
        wordPath: '',
        status: '',
        userId: '',
        selectedModels:[],
        detailList: this.tableData
      },
      selectDis:false,
      // 表格数据
      tableData: [],
      // 仪器设备列表
      instrumentList: [],
      // 项目编号列表
      projectList: [],
      dataRule: {
        projectNumber: [
          { required: true, message: '项目编号不能为空', trigger: 'blur' }
        ],
        dataTime: [
          { required: true, message: '检测日期不能为空', trigger: 'blur' }
        ],
        inspector: [
          { required: true, message: '检测人不能为空', trigger: 'blur' }
        ],
        notekeeper: [
          { required: true, message: '记录人不能为空', trigger: 'blur' }
        ],
        checker: [
          { required: true, message: '核校人不能为空', trigger: 'blur' }
        ],
        pdfPath: [
          { required: true, message: 'pdf路径不能为空', trigger: 'blur' }
        ],
        wordPath: [
          { required: true, message: 'word路径不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '审核状态不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '用户ID不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getInstrument(),
      this.getprojectList()
  },
  methods: {
    handleDateChange(scope) {
      // 如果有效期是一个数组，格式化并更新表单数据
      if (Array.isArray(scope.row.indate) && scope.row.indate.length === 2) {
        const startDate = scope.row.indate[0];
        const endDate = scope.row.indate[1];

        // 将格式化后的日期传入表单
        scope.row.indate = [this.formatDate(startDate), this.formatDate(endDate)];
      }
    },

    // 格式化日期为 yyyy-MM-dd
    formatDate(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从0开始
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    },
    handleModelSelectionChange() {
      // 获取选中的所有模型
      const selectedModels = this.dataForm.selectedModels;


      // 遍历所有仪器型号，如果当前型号没有在选中的列表中，则移除
      this.tableData = this.tableData.filter(item => selectedModels.includes(item.instrumentNumber));

      // 遍历选中的仪器型号，如果该型号还没有在表格中，则添加它
      selectedModels.forEach(instrumentNumber => {
        // 判断该仪器型号是否已存在于表格中
        if (!this.tableData.some(item => item.instrumentNumber === instrumentNumber)) {
          const selectedModel = this.instrumentList.find(item => item.instrumentNumber === instrumentNumber);
          if (selectedModel) {
            // 将选中的仪器型号添加到表格
            this.tableData.push({
              instrumentName: selectedModel.instrumentName,
              instrumentNumber: selectedModel.instrumentNumber,
              keyInstrument: selectedModel.accuracyRating,
              valueTa: selectedModel.measuringRange,
              indate: '',
            });
          }
        }
      });
    },
    getInstrument() {
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/instrument/getInstrument`),
        method: 'post',
        data: this.$http.adornData({
        })
      }).then((data) => {
        if (data && data.code === 0) {
          console.log(data.productList)
          this.instrumentList = data.instrumentList
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    getprojectList() {
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
        method: 'post',
        data: this.$http.adornData({
        })
      }).then((data) => {
        if (data && data.code === 0) {
          console.log(data.productList)
          this.projectList = data.productList
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    init(id) {
      this.dataForm.id = id || 0
      this.selectDis = false
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.tableData = []
        this.dataForm.selectedModels=[]
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/keyinstrument/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.projectNumber = data.keyInstrument.projectNumber
              this.dataForm.dataTime = data.keyInstrument.dataTime
              this.dataForm.inspector = data.keyInstrument.inspector
              this.dataForm.notekeeper = data.keyInstrument.notekeeper
              this.dataForm.checker = data.keyInstrument.checker
              this.dataForm.pdfPath = data.keyInstrument.pdfPath
              this.dataForm.wordPath = data.keyInstrument.wordPath
              this.dataForm.status = data.keyInstrument.status
              this.dataForm.userId = data.keyInstrument.userId
              this.selectDis = true
              //处理下拉框回显
              this.dataForm.selectedModels =data.keyInstrument.detailList.map(item => {

              return item.instrumentNumber;
              });
              // 处理 detailList 中的 indate 字段
              this.tableData = data.keyInstrument.detailList.map(item => {
                if (item.indate) {
                  // 假设 indate 格式为 "yyyy-mm-dd ~ yyyy-mm-dd"
                  const dateRange = item.indate.split(' ~ ');
                  if (dateRange.length === 2) {
                    item.indate = [dateRange[0], dateRange[1]];
                  }
                }
                return item;
              });
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      // 在提交前，可以通过 detailList 对象处理所有的日期字段
      this.tableData.forEach(item => {
        if (item.indate && Array.isArray(item.indate) && item.indate.length === 2) {
          // 你可以选择存储原始的数组格式或者格式化后的字符串
          item.indate = `${item.indate[0]} ~ ${item.indate[1]}`;

        }
      });
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/keyinstrument/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'projectNumber': this.dataForm.projectNumber,
              'dataTime': this.dataForm.dataTime,
              'inspector': this.dataForm.inspector,
              'notekeeper': this.dataForm.notekeeper,
              'checker': this.dataForm.checker,
              'pdfPath': this.dataForm.pdfPath,
              'wordPath': this.dataForm.wordPath,
              'status': this.dataForm.status,
              'userId': this.dataForm.userId,
              'detailList': this.tableData
            })
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.warning(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
/* 为表头添加背景色 */
::v-deep .el-table__header {
  background-color: #f5f5f5;
  /* 你可以修改为任何颜色 */
}
</style>
